package com.douwong.student.popuwindow;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

import com.douwong.student.R;
import com.douwong.student.view.ScaleImageView;

import java.io.File;

public class ImageShowPopu extends PopupWindow {

	private ScaleImageView img;
	private View view;
	public ImageShowPopu(Context context, Bitmap bitmap, int width, int height) {
		LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view=inflater.inflate(R.layout.image_show, null);
		initView(bitmap,width,height);
	}

	public ImageShowPopu(Context context, String imgPath, int width, int height){
		LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view=inflater.inflate(R.layout.image_show, null);
		Bitmap bitmap=null;
		File file = new File(imgPath);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds=true;
		BitmapFactory.decodeFile(imgPath, options);


		options.inSampleSize=calculateInSampleSize(options,width,height);
		options.inJustDecodeBounds=false;
		bitmap=	BitmapFactory.decodeFile(imgPath, options);

		if (bitmap != null) {
			initView(bitmap,width,height);
		}


		
	}
	void initView(Bitmap bitmap,int width,int height){
		img=(ScaleImageView) view.findViewById(R.id.img);
		img.setDispResource(bitmap, width, height);
		img.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
		this.setContentView(view);
		this.setWidth(LayoutParams.MATCH_PARENT);
		this.setHeight(LayoutParams.MATCH_PARENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		this.setFocusable(true);
		ColorDrawable dw = new ColorDrawable(0xffffff);
		this.setBackgroundDrawable(dw);



	}
	/**
	 * 计算缩放比例
	 * @param op
	 * @param reqWidth
	 * @param reqheight
	 * @return
	 */
	public int calculateInSampleSize(BitmapFactory.Options op, int reqWidth,
									 int reqheight) {
		int originalWidth = op.outWidth;
		int originalHeight = op.outHeight;
		int inSampleSize = 1;
		if (originalWidth > reqWidth || originalHeight > reqheight) {
			int halfWidth = originalWidth / 2;
			int halfHeight = originalHeight / 2;
			while ((halfWidth / inSampleSize > reqWidth)
					&&(halfHeight / inSampleSize > reqheight)) {
				inSampleSize *= 2;

			}
		}
		return inSampleSize;
	}
}
